package com.gaogzhen.juc.atomic.Reference;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

@Slf4j(topic = "c.TestABA")
public class TestABAStamped {
    static AtomicStampedReference<String> ref = new AtomicStampedReference<>("A", 0);
    public static void main(String[] args) throws InterruptedException {
        log.debug("main start ...");
        // 获取值A
        String prev = ref.getReference();
        int stamp = ref.getStamp();
        other();
        TimeUnit.SECONDS.sleep(1);
        // 尝试更改为C
        log.debug("change A->C {},stamp {}->{}", ref.compareAndSet(prev, "C", stamp, stamp + 1), stamp, stamp + 1);

    }

    private static void other() {
        new Thread(() -> {
            int stamp = ref.getStamp();
            log.debug("change A->B {},stamp {}->{}", ref.compareAndSet(ref.getReference(), "B", stamp, stamp + 1), stamp, stamp + 1);
        }, "t2").start();

        try {
            TimeUnit.MILLISECONDS.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            int stamp = ref.getStamp();
            log.debug("change B->A {},stamp {}->{}", ref.compareAndSet(ref.getReference(), "A", stamp, stamp + 1), stamp, stamp + 1);
        }, "t2").start();
    }
}
